<template>
    <div class="table-warp">
        <!-- 表格START -->
        <div class="table" style="top:10px;">
            <div class="table-container" :style="_gettableMinWidth">
                <div class="table-thead" v-show="_thead && _thead.length>0">
                    <Row type="flex">
                        <div class="checkboxWarp" v-if="hasCheckbox">
                            <i class="checkbox" :class="{
                                   'checkbox-checked': itemAllChecked,
                                   'checkbox-part-checked': hasItemChecked && !itemAllChecked
                                }"
                                @click="checkAll"></i>
                        </div>
                        <div class="checkboxWarp" v-if="hasIndex">
                            <span class="index">{{indexName}}</span>
                        </div>
                        <Col class="table-flex-col" v-for="(thItem, th_index) in _thead"
                             :key="th_index"
                             :name="thItem.name"
                             :class="{'flex1': !thItem.width}"
                             :style="{
                                'width' : thItem.width ? thItem.width + 'px':'auto',
                                'text-align' : thItem.align ?  thItem.align : 'center'
                             }"
                            >
                            <div class="table-th">
                                <span class="column-title" :title="thItem.title" :style="{'width' : !!thItem.sortFilter ? 'auto' : ''}">{{thItem.title}}</span>
                                <span class="sortWrap" v-show="!!thItem.sortFilter" :class="{'active' : thItem.sortFilter !== 'asc'}" @click.stop="sortClick(thItem)">
                                  <Icon type="android-arrow-dropup" class="arrowup"/>
                                  <Icon type="android-arrow-dropdown" class="arrowdown"/>
                                </span>
                            </div>
                        </Col>
                    </Row>
                </div>

                <div class="table-tdata" v-if="tdata && tdata.length > 0">
                    <div class="table-row" v-for="(td, index) in tdata"
                        :key="index"
                         @click="clickRow($event, td, index)">
                        <Row type="flex">
                            <div class="checkboxWarp" v-if="hasCheckbox">
                                <i class="checkbox"
                                   :class="{'checkbox-checked': td.checked}"
                                   @click="checkItem($event, td)">
                                </i>
                            </div>
                            <div class="checkboxWarp" v-if="hasIndex">
                                <span class="index">{{pagerData.startRow + index}}</span>
                            </div>
                            <Col v-for="(th, index_th) in _thead"
                                 :key="index_th"
                                 class="table-flex-col"
                                 :class="{'flex1': !th.width}"
                                 :style="{
                                    'width' : th.width ? th.width + 'px':'auto',
                                    'text-align' : th.align ?  th.align : 'center'
                                 }">

                                <div v-if="th.render" class="table-flex-col_div" :title="td[th.name]">
                                    <cell :column="th" :row="td" :naturalIndex="pagerData.startRow + index + td['id']"></cell>
                                </div>
                                <div v-else-if="th.img" class="table-flex-col_div img_box" :title="td[th.name]">
                                    <img :src="td[th.name]" alt="" v-if="td[th.name]">
                                    <img src="http://test.shhxfyl.com/image/default/BA7EDA2214C144AD9C94228999EEB579-6-2.png" alt="" v-if="!td[th.name]">
                                </div>
                                <div v-else class="table-flex-col_div" :title="td[th.name]">
                                    <span>{{ td[th.name] }}</span>
                                </div>
                            </Col>
                        </Row>
                    </div>
                </div>
                <!-- 暂无数据 -->
                <div v-if="!loading && tdata.length < 1" class="reportTablenodata">
                    <div class="table-nodata alert">
                        <i></i> 暂无数据
                    </div>
                </div>
            </div>
            <!-- 加载中START -->
            <div class="c-loadingwarp" v-if="loading">
                <div class="c-gridTableloading">
                    <div class="c-gridTableDemo-spin-col">
                        <Spin fix>
                            <Icon type="load-c" size="22" class="c-demo-spin-icon-load"></Icon>
                            <div>正在加载</div>
                        </Spin>
                    </div>
                </div>
            </div>
        </div>

        <!-- 分页START -->
        <div class="table-tfoot" v-if="isPageShow && pagerData.total !== 0">
            <Row>
                <div class="clear"></div>
                <div class="totalCount">
                    当前第 {{pagerData.current}}页，
                    当前第 {{pagerData.startRow}} 到第 {{pagerData.endRow}}条，
                    共 {{pagerData.total}} 条
                </div>
                <Page ref="refPager" class="pager" show-sizer show-elevator
                      :current="pagerData.current"
                      :total="pagerData.total"
                      :pageSize="pagerData.rows"
                      :pageSizeOpts="rowOptions"
                      placement="top"
                      @on-change="pageChange"
                      @on-page-size-change="rowChange">
                </Page>
            </Row>
        </div>
        <!-- 分页END -->
    </div>
</template>
<script>
    import cell from './cell';
    import { apiPost } from '@/common/http';
    export default {
        data() {
            return {
                hasItemChecked: false, // 是否部分选中
                itemAllChecked: false, // 是否全选
                checkedItemCount: 0, // 选中个数
                loading: true, // 加载效果
                tdata: [], // 数据列表
                _thead: [], // 标题 这里会动态更改
                rowOptions: [10, 15, 30, 50], // 每页显示数
                pagerData: {
                    current: 1,
                    page: 1,
                    startRow: 0,
                    endRow: 0,
                    total: 0,
                    rows: 12
                }
            };
        },
        components: { cell },
        computed: {
            // 计算表格宽度
            _gettableMinWidth() {
                let width = 0;
                console.log("获取表头的父子数据~~~~~~~~~~~~~",this._thead);
                this._thead.forEach(item => {
                    let curWidth = item.width ? item.width : 350;
                    width += curWidth;
                });
                return `min-width:${width}px`;
            }
        },
        methods: {
            // 排序点击
            sortClick(item) {
                let sort = item.sortFilter !== 'asc' ? 'asc' : 'desc'
                item.sortFilter = sort
                this.$emit('sortEmit', item.name, sort);
            },
            // 点击行
            clickRow(e, rowData, index) {
                this.$emit('clickRow', rowData, index);
            },
            // 点击分页
            pageChange(page) {
                this.pagerData.page = page;
                this.refreshList();
            },
            // 切换分页数
            rowChange(rows) {
                this.pagerData.rows = rows;
                this.getList();
            },
            // 初始化
            init() {
                this.itemAllChecked = false; // 全选初始化
                this.hasItemChecked = false; // 部分选中初始化
                this.refreshList();
            },
            // 选择复选框
            checkItem(e, item) {
                var allcheckedList = [];
                var checkedList = [];
                var uncheckedList = [];
                item.checked = !item.checked;
                this.updateCheckedStats();
                if (e) {
                    e.stopPropagation();
                }
                // this.tdata.forEach(item => {
                if (item.checked) checkedList.push(item);
                else uncheckedList.push(item)
                // });
                this.tdata.forEach(item => {
                    if (item.checked) allcheckedList.push(item);
                });
                this.$emit('selection-change',allcheckedList, uncheckedList, checkedList);
            },
            // 全选
            checkAll(e) {
                var checkedList = [];
                var uncheckedList = [];
                if (this.itemAllChecked) {
                    this.tdata.forEach(function(item) {
                        item.checked = false;
                    });
                } else {
                    this.tdata.forEach(function(item) {
                        item.checked = true;
                    });
                }
                this.updateCheckedStats();
                if (e) {
                    e.stopPropagation();
                }
                this.tdata.forEach(item => {
                    if (item.checked) checkedList.push(item);
                    else uncheckedList.push(item)
                });
                this.$emit('selection-change', checkedList, uncheckedList);
            },
            // 全部不选
            uncheckAll(e) {
                var checkedList = [];
                var uncheckedList = [];
                // 未全选，全选
                this.tdata.forEach(function(item) {
                    item.checked = false;
                });
                this.updateCheckedStats();
                if (e) {
                    e.stopPropagation();
                }
                this.tdata.forEach(item => {
                    if (item.checked) checkedList.push(item);
                    else uncheckedList.push(item)
                });
                this.$emit('selection-change', checkedList, uncheckedList, 'radios');
            },
            // 更新选中状态
            updateCheckedStats() {
                var _this = this;
                _this.checkedItemCount = 0;
                if (this.tdata && this.tdata.length > 0) {
                    this.itemAllChecked = this.tdata.every(item => item.checked);
                    this.hasItemChecked = this.tdata.some(item => item.checked);
                    this.tdata.forEach(item => {
                        if (item.checked) _this.checkedItemCount++;
                    });
                } else {
                    this.itemAllChecked = false;
                    this.hasItemChecked = false;
                    this.checkedItemCount = 0;
                }
                this.$forceUpdate();
            },
            // 刷新列表
            refreshList() {
                const _this = this;
                console.log("获取比偶213213123123",_this.thead);
                _this._thead = _this.thead.length > 0 ? _this.thead : _this.theadFun;
                // _this.loading = true; // 有全局加载，这里暂且隐藏
                const pageParams = {
                    page: _this.pagerData.page,
                    rows: _this.pagerData.rows
                }
                const filterParams = this.filterFun();
                const params = Object.assign(pageParams, filterParams);
                const listApi = this.listApi ? this.listApi : this.listApiFun;
                apiPost(listApi, params).then((resData) => {
                    _this.loading = false;
                    _this.tdata = [];
                    console.log("表格数据```````````",resData);
                    _this.beforePageFun(_this.pagerData.page);
                    if (resData && resData.list.length > 0) {
                        resData.list.forEach((item,index) => {
                            item.serial = (index+1)+((_this.pagerData.page-1)*_this.pagerData.rows);
                            _this.tdata.push(_this.formatFun(item));
                            if (listApi === 'order/api/v1.2/report/list') {
                                item.customerPhoneCopy = item.customerPhone
                                item.customerPhone = item.customerPhone && (item.customerPhone.substr(0,3) + "****" + item.customerPhone.substr(7)) || '-'
                            }
                            if (listApi === '/tospurWeb/api/InvitationCustomerInfo/getPageInvaitationCustomerInfo') {
                                if (item.customerInfoName === item.customerInfoPhone) {
                                    item.customerInfoName = item.customerInfoName && (item.customerInfoName.substr(0,3) + "****" + item.customerInfoName.substr(7)) || '-'
                                }
                                item.customerInfoPhone = item.customerInfoPhone && (item.customerInfoPhone.substr(0,3) + "****" + item.customerInfoPhone.substr(7)) || '-'
                            }
                            if (listApi === '/order/api/orders/list') {
                                item.orderTypeName = item.orderType == 1 ? '报备订单' : item.orderType == 2 ? '带看订单' :  item.orderType == 3 ? '认筹订单' :  item.orderType == 4 ? '退筹订单' :  item.orderType == 5 ? '认筹订单' : item.orderType == 6 ? '退购订单' : item.orderType == 7 ? '签约订单' :  item.orderType == 8 ? '退签订单' : '-';
                                item.auditStatusName = item.auditStatus == 1 ? '未审核' : item.auditStatus == 2 ? '通过审核' :  item.auditStatus == 3 ? '审核驳回' :  item.auditStatus == 4 ? '待确认' :  item.auditStatus == 5 ? '有效报备' : '-';
                                item.phoneSiHide = item.phone && (item.phone.substr(0,3) + "****" + item.phone.substr(7)) || '-'
                                if (item.phone === item.userCustomerName) {
                                    item.userCustomerName = item.userCustomerName && (item.userCustomerName.substr(0,3) + "****" + item.userCustomerName.substr(7)) || '-'
                                }
                            }
                        });
                    }
                    _this.pagerData.startRow = Number(resData.startRow);
                    _this.pagerData.total = Number(resData.total);
                    _this.pagerData.current = Number(resData.pageNum);
                    console.log('resData.pageSize', resData.pageSize)
                    // _this.pagerData.rows = Number(resData.pageSize);
                    _this.pagerData.page = Number(resData.pageNum);
                    _this.pagerData.endRow = Number(resData.endRow);
                    _this.isEndRow =  Number(resData.endRow);
                    _this.pagerData.lastPage = Boolean(resData.lastPage);
                    console.log("分页数据",_this.pagerData);
                    _this.afterPageFun(_this.pagerData.page);
                    // 告诉父组件table是不是为空
                    _this.$emit('tableIsEmpty',_this.tdata.length)
                    // 因判断父组件需要
                    _this.$emit('tableIsTotal',_this.pagerData.total)

                }, (err) => {
                    _this.loading = false;
                    // console.log(err);
                });
            },
            noGet() {
                const _this = this;
                _this._thead = _this.thead.length > 0 ? _this.thead : _this.theadFun;
                _this.loading = false;
                _this.tdata = [];
            },
            // 获取列表
            getList() {
                this.pagerData.page = 1;
                this.refreshList();
            },
            reloadData () {
              Object.assign(this.$data, this.$options.data())
            }
        },
        created() {
            if (this.requestInit) {
                this.init();
            } else {
                this.noGet();
            }
        },
        props: {
            // 是否展示多选框
            hasCheckbox: {
                type: Boolean,
                default: true
            },
            // 是否展示序号
            hasIndex: {
                type: Boolean,
                default: true
            },
            // 序号标题
            indexName: {
                type: String,
                default: '序号'
            },
            // 是否立即请求列表
            requestInit: {
                type: Boolean,
                default: true
            },
            // 是否显示分页
            isPageShow: {
                type: Boolean,
                default: true
            },
            // 是否显示分页
            filterFun: {
                type: Function,
                default: () => {
                    return {};
                }
            },
            // 格式化数据
            formatFun: {
                type: Function,
                default: (obj) => {
                    return obj;
                }
            },
            // 加载分页前初始化
            beforePageFun: {
                type: Function,
                default: () => {}
            },
            // 加载分页后初始化
            afterPageFun: {
                type: Function,
                default: () => {}
            },
            // 页头
            thead: {
                type: Array,
                default: []
            },
            // 动态页头
            theadFun: {
                type: Function,
                default: () => {}
            },
            // 列表接口
            listApi: {
                type: String,
                default: ''
            },
            // 动态列表接口
            listApiFun: {
                type: Function,
                default: () => {}
            }
        }
    };
</script>
<style lang="scss" scoped>
    @import "~@/assets/sass/install";
    @import "~@/assets/sass/_resetView.scss";

    .textcenter {
        width: 100%;
        text-align: center;
    }

    .formList {
        width: 100%;
        margin-top: 38px;
        border: none;
    }

    .protect {
        overflow: hidden;
    }

    .protect div {
        float: left;
        height: 34px;
        line-height: 34px;
        font-size: 15px;
        color: #86888a;
    }

    .protect input {
        float: left;
        width: 310px;
        text-align: center;
    }

    .table table {
        width: 100%;
        margin-top: 28px;
        font-size: 14px;
        border-collapse: collapse;
    }

    .formList table th {
        color: #0e0e0e;
        vertical-align: middle;
    }

    .formList table th {
        font-size: 15px;
    }

    .formList table td,
    .formList table th {
        padding: 10px 15px;
        border: 1px solid #dddfe2;
    }

    .formList table tr:nth-child(even) {
        background-color: #fff;
    }

    .formList table td {
        vertical-align: middle;
        text-align: center;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }

    .formList table td,
    .formList table th {
        padding: 10px 15px;
        border: 1px solid #dddfe2;
    }

    .formList table input[type=text] {
        height: 26px;
        line-height: 26px;
        width: 50%;
        text-align: center;
        color: #8f9193;
        background: 0 0;
    }

    .titleTab {
        color: #5e5f5f;
        font-size: 16px;
        height: 48px;
        line-height: 48px;
        width: 100%;
        float: left;
        width: 300px;
    }

    .titleTab div {
        float: left;
        height: 100%;
        width: 120px;
        text-align: center;
        cursor: pointer;
    }

    .titleTab div.active {
        color: #02b0f0;
        position: relative;
    }

    .sortWrap{
        display: inline-block;
        height: 100%;
        &.active{
            .arrowup{
                color: #333;
            }
            .arrowdown{
                color: #999;
            }
        }
        i{
            display: block;
            font-size: 19px;
            font-weight: bold;
            height: 20px;
            width: 10px;
            line-height: normal;
            &.arrowup{
                color: #999;
                line-height: 35px;
            }
            &.arrowdown{
                color: #333;
                line-height: 10px;
            }
        }
    }
    .table-warp {
        position: relative;
        height: 100%;
        width: 100%;
        overflow: auto;
        .table {
            // position: absolute;
            // top: 0px;
            // right: 0;
            // left: 0;
            // bottom: 0;
            border: 1px solid $thBorderColor;
            background: url(./grid-bg.png) repeat 0 0;
            @include overflowCss();
            // overflow-x: auto;
            // overflow-y: hidden;

            .table-container {
                background-color: white;
                position: absolute;
                left: 0;
                right: 0;
                top: 0;
                bottom: 0px;
                padding-top: 48px;

                .checkboxWarp {
                    width: 50px;
                    text-align: center;
                    height: 40px;
                    line-height: 40px;
                    color: #8c8b8b;
                }
            }

            .table-thead {
                position: absolute;
                left: 0;
                top: 0;
                width: 100%;
                padding-right: 10px;

                &:after {
                    position: absolute;
                    right: 0;
                    top: 0;
                    content: '';
                    width: 10px;
                    height: 40px;
                    background-color: #f5f5f5;
                    border-bottom: 1px solid #ddd;
                }

                ;

                /*z-index: 1;*/
                &:hover {
                    .ivu-col {
                        .table-filter-container {
                            display: inline-block;
                        }
                    }
                }

                .ivu-col {
                    height: 40px;
                    line-height: 40px;
                    background-color: $thBG;
                    border-bottom: 1px solid $thBorderColor;
                    text-align: center;
                    cursor: pointer;
                    padding: 0 10px;

                    &.last-child {
                        border-left: 1px solid $thBorderColor;
                        display: flex;
                        align-items: center;
                        justify-content: center;
                    }

                    .table-filter-container {
                        display: inline-block;
                        padding: 0 8px;
                    }

                    .setting {
                        display: inline-block;
                        width: 21px;
                        height: 21px;
                    }

                    .index {
                        color: #666666;
                        font-weight: bold;
                    }

                    .table-th {
                        height: 100%;
                        position: relative;

                        .column-title {
                            display: inline-block;
                            vertical-align: top;
                            color: #666666;
                            font-weight: bold;
                            width: 100%;
                            white-space: nowrap;
                            text-overflow: ellipsis;
                            overflow: hidden;
                        }
                    }
                }
                .checkboxWarp {
                    background-color: #f5f5f5;
                    border-bottom: 1px solid #d5d5d5;
                    font-weight: bold;
                    color: #666666;
                }
            }

            .table-tdata {
                overflow-y: scroll;
                position: absolute;
                left: 0;
                right: 0;
                top: 40px;
                bottom: 60px;
                background: url(./grid-bg.png) repeat 0 0;
                background-size: 1px 41px;

                .table-row {
                    background-color: white;
                    border-bottom: 1px solid $tdBorderColor;
                    @include transition(500ms, background-color);
                    cursor: pointer;
                    &.active {
                        background-color: $tdBorderColor;
                    }

                    &:last-child {
                        border-bottom: none;
                    }

                    &:hover {
                        background-color: $tdBorderColor;
                    }

                    .table-flex-col_hover {
                        color: #02b0f0;

                        .table-flex-col_div {
                            display: flex;
                            cursor: pointer;
                            height: 40px;
                            align-items: center;
                        }
                    }

                    .tip_icon {
                        display: inline-block;
                        vertical-align: middle;
                        margin-top: 1px;
                        width: 18px;
                        height: 20px;
                        background: url(./icons.png) no-repeat -461px -1045px;
                    }
                }

                .table-row_nocursor {
                    cursor: default;
                }

                .ivu-col {
                    height: 40px;
                    padding: 0 10px;
                    color: #8c8b8b;
                    display: flex;
                    flex-direction: row;
                    justify-content: flex-start;
                    align-items: center;

                    span {
                        display: inline-block;
                        vertical-align: middle;
                        max-width: 100%;
                        white-space: nowrap;
                        text-overflow: ellipsis;
                        overflow: hidden;
                    }
                }

                .table-flex-col {
                    overflow: hidden;
                    .table-flex-col_div {
                        white-space: nowrap;
                        overflow: hidden;
                        text-overflow: ellipsis;
                        line-height: 40px;
                        width: 100%;
                            &.img_box{
                              margin: 0 auto;
                              width: 40px !important;
                              height: 40px !important;
                              border-radius: 50%;
                              img{
                                width: 100%;
                                height: 100%;
                              }
                            }
                    }
                }

                @include overflowCss();
            }

            .reportTablenodata {
                position: absolute;
                top: 0;
                left: 0;
                right: 0;
                bottom: 0;
                color: #8f8f8f;

                .alert {
                    text-align: center;
                    position: fixed;
                    width: 240px;
                    left: 50%;
                    top: 50%;
                    margin-left: -10px;
                    margin-top: -50px;
                    i {
                        display: block;
                        width: 78px;
                        height: 90px;
                        border-radius: 50px;
                        margin: 0 auto;
                        background: url(./customer_icons.png) no-repeat -218px -490px;
                        margin-bottom: 5px;
                    }
                }

                .table-nodata {
                    i {
                        background: url(./customer_icons.png) no-repeat -141px -480px;
                    }
                }

                .modalAlert {
                    margin-left: -120px;
                }
            }
        }
    }

    .table-tfoot {
        width: 100%;
        position: absolute;
        left: 0;
        right: 20px;
        bottom: 10px;
        height: 49px;

        .ivu-row {
            border: 1px solid $thBorderColor;
            border-bottom: 0;
            padding: 8px 15px 4px 15px;
            background-color: #fff;
        }

        .clear {
            display: inline-block;
            height: 32px;
            line-height: 32px;
        }

        .totalCount {
            position: absolute;
            height: 32px;
            line-height: 32px;
            display: inline-block;
            vertical-align: top;
            color: #657180;
        }

        .pager {
            display: inline-block;
            vertical-align: top;
            position: absolute;
            right: 20px;
            background-color: #fff;
            padding-left: 50px;
        }
    }
    .flex1{
        flex: 1
    }
</style>
